class Solution {
    public String countAndSay(int n) {
        //双指针算法
        String s = "1";
        for(int i = 2; i <= n; i++){
            int left = 0;
            int right = 0;
            StringBuilder next = new StringBuilder();
            while(right < s.length()){
                char ch1 = s.charAt(left);
                char ch2 = s.charAt(right);
                if(ch1 == ch2){
                    right++;
                }else{
                    next.append(right - left);
                    next.append(ch1);
                    left = right;
                }
            }
            next.append(right - left);
            next.append(s.charAt(left));
            s = next.toString();
        }
        return s;
    }
    public String countAndSay1(int n) {
        StringBuilder stringBuilder1 = new StringBuilder("1");
        for(int i = 2; i <= n; i++){
            StringBuilder stringBuilder2 = new StringBuilder();
            int count = 1;
            for(int j = 0; j < stringBuilder1.length() - 1; j++){
                char ch1 = stringBuilder1.charAt(j);
                char ch2 = stringBuilder1.charAt(j+1);
                if(ch1 == ch2){
                    count++;
                }else{
                    stringBuilder2.append(count);
                    stringBuilder2.append(ch1);
                    count = 1;
                }
            }
            stringBuilder2.append(count);
            stringBuilder2.append(stringBuilder1.charAt(stringBuilder1.length() - 1));
            stringBuilder1 = stringBuilder2;
        }
        return stringBuilder1.toString();
    }
}